package igou.togogo.service.impl;


import igou.togogo.bean.*;
import igou.togogo.common.service.impl.BaseServiceImpl;
import igou.togogo.param.CartParam;
import igou.togogo.pojo.EgouResult;
import igou.togogo.service.ICartService;
import igou.togogo.utils.HttpClientUtil;
import igou.togogo.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class CartServiceImpl extends BaseServiceImpl implements ICartService {

    @Override
    public BuyCart add(String carCookie, CartParam param) {
        Integer skuId = param.getSkuId();
        Integer productId = param.getProductId();
        Integer num = param.getNum();
        BuyCart buyCart = new BuyCart();
        //判断cookie内是否存在购物车 若存在 直接使用
        if (StringUtils.isNotBlank(carCookie)) {
            buyCart = JsonUtils.jsonToPojo(carCookie, BuyCart.class);
        }
        //skuid
        if (skuId != null) {
            BuyItem buyItem = new BuyItem();
            String skuJson = HttpClientUtil.doGet(REST_BASE_URL + SKU_URL + skuId);
            //查询库存
            if (StringUtils.isNotBlank(skuJson)) {
                EgouResult skuResult = EgouResult.formatToPojo(skuJson, ESku.class);
                buyItem.setSku((ESku) skuResult.getData());
            }
            //查询商品
            String productJson = HttpClientUtil.doGet(REST_BASE_URL + PRODUCT_URL + productId);
            if (StringUtils.isNotBlank(productJson)){
                EgouResult productResult = EgouResult.formatToPojo(productJson, EProduct.class);
                buyItem.setProduct((EProduct) productResult.getData());
            }
            //查询商品图片
            String imgJson = HttpClientUtil.doGet(REST_BASE_URL + IMG_MAIN_URL + productId);
            if (StringUtils.isNotBlank(imgJson)){
                EgouResult imgResult = EgouResult.formatToPojo(imgJson, EImg.class);
                buyItem.setImg((EImg) imgResult.getData());
            }
            buyItem.setAmount(num);
            buyCart.addItem(buyItem);
            buyCart.setProductId(productId);
            return buyCart;
        }
        return null;
    }

}
